﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Trade.Journal.Controls
{
    public class ClauseBox : TextBox
    {
        static ClauseBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ClauseBox), new FrameworkPropertyMetadata(typeof(ClauseBox)));
        }

        private ListView PART_List;


        //public string[] Marks
        //{
        //    get
        //    {
        //        return (PART_List.ItemsSource as IEnumerable<string>)?.ToArray();
        //    }
        //    set
        //    {
        //        if (PART_List != null)
        //            PART_List.ItemsSource = new ObservableCollection<string>(value);
        //    }
        //}



        public IEnumerable<string> Clauses
        {
            get { return (IEnumerable<string>)GetValue(ClausesProperty); }
            set { SetValue(ClausesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Clauses.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ClausesProperty =
            DependencyProperty.Register("Clauses", typeof(IEnumerable<string>), typeof(ClauseBox), new FrameworkPropertyMetadata(new ObservableCollection<string>()));




        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (Clauses == null) Clauses = new ObservableCollection<string>();
            PART_List = Template.FindName(nameof(PART_List), this) as ListView;
            CommandBindings.Add(new CommandBinding(Commands.DeleteCommand, new ExecutedRoutedEventHandler(DeleteCommand_Executed)));
        }

        private void DeleteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter is string str)
            {
                if (PART_List?.ItemsSource is ICollection<string> s)
                    s.Remove(str);
            }
        }

        protected override void OnPreviewKeyUp(KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                if (!string.IsNullOrWhiteSpace(Text) && Clauses is ICollection<string> s)
                {
                    s.Add(Text); 

                    if (PART_List != null)
                    {
                        if (!(Clauses is INotifyCollectionChanged))
                            PART_List.Items.Refresh();
                        PART_List.ScrollIntoView(PART_List.Items.GetItemAt(PART_List.Items.Count - 1));
                    }
                }
                Text = string.Empty;
            }
            base.OnPreviewKeyUp(e);
        }




    }
}
